package com.jzg.jcptadmin.ui;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewStub;
import android.widget.ImageView;
import android.widget.TextView;

import com.jzg.jcptadmin.R;
import com.jzg.jcptadmin.Utils.MyToast;
import com.jzg.jcptadmin.adpter.KuaiSuOnlineAdapter;
import com.jzg.jcptadmin.app.ActivityHelp;
import com.jzg.jcptadmin.base.BaseActivity;
import com.jzg.jcptadmin.constant.Constant;
import com.jzg.jcptadmin.data.DataManager;
import com.jzg.jcptadmin.data.local.LocalData;
import com.jzg.jcptadmin.data.vo.CarDetails;
import com.jzg.jcptadmin.data.vo.FastOnlineData;
import com.jzg.jcptadmin.data.vo.PopListDataModel;
import com.jzg.jcptadmin.data.vo.StatusData;
import com.jzg.jcptadmin.data.vo.User;
import com.jzg.jcptadmin.presenter.KuaiSuOnLinePresenter;
import com.jzg.jcptadmin.view.PopWindowView;
import com.jzg.jcptadmin.viewinterface.KuaiSuOnlineInterface;
import com.jzg.template.refreshrecycleview.DividerItemDecoration;
import com.jzg.template.refreshrecycleview.RefreshBaseAdapter;
import com.jzg.template.refreshrecycleview.RefreshRecycleView;
import com.orhanobut.logger.Logger;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.pedant.SweetAlert.SweetAlertDialog;

/**
 * 评估师端快速线上页面
 * KuaiSuOnLineActivity
 *
 * @author sunbl
 *         created at 2016/1/21 16:10
 */
public class KuaiSuOnLineActivity extends BaseActivity implements KuaiSuOnlineInterface,
        RefreshRecycleView.OnStateChangeLstener {
    @Bind(R.id.fast_title_defaultsort)
    TextView filter_date;
    @Bind(R.id.fast_advanced_filter)
    TextView filter_status;
    @Bind(R.id.fast_empty_view)
    ViewStub fastEmptyView;
    @Bind(R.id.fast_hintline)
    View fastHintline;
    @Bind(R.id.fast_online_recycler)
    RefreshRecycleView fastOnlineRecycler;
    @Bind(R.id.title_content)
    TextView titleContent;
    @Bind(R.id.title_searchbyvin)
    ImageView search;

    private String[] youmeng = new String[]{"pinggushi_xianshangquanbuzhuangtai", "pinggushi_xianshangdaipingguzhuangtai",
            "pinggushi_xianshangchaoshizhuangtai", "pinggushi_xianshangyiquerenzhuangtai", "pinggushi_xianshangbeibohuizhuangtai",
            "pinggushi_xianshangyipingguzhuangtai", "pinggushi_xianshangyishenhezhuangtai",
            "pinggushi_xianshangyiqianshouzhuangtai", "pinggushi_xianshangyishanchuzhuangtai"};//友盟统计埋点
    private PopWindowView pop;
    private List<FastOnlineData.AppraiseListEntity> mDatas = new ArrayList<>();
    public KuaiSuOnLinePresenter presenter;
    private KuaiSuOnlineAdapter adapter;
    //数据类型 2今日任务  3昨天任务  1全部任务 默认今日任务
    private int datetype = Constant.ALL_TASK;

    //点击全部状态的id  默认-2
    private String status = "-2";
    private FastOnlineData.AppraiseListEntity currEntity;

    /**
     * (0默认，1刷新，2加载)
     */
    private int operation = Constant.LISTVIEW_DEFAULT;
    private StatusData statusData;
    private User user;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_kuai_su_on_line);
        ButterKnife.bind(this);
        titleContent.setText("快速线上评估");
        filter_date.setText("全部任务");
        search.setVisibility(View.VISIBLE);
        statusData = appContext.getStatus();
        user = appContext.getUser();
        presenter = new KuaiSuOnLinePresenter(DataManager.getInstance());
        presenter.attachView(this);
        initData();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        //默认加载列表
        onRefresh();
    }

    private void initData() {
//        pop = new PopWindowView(this, filter_date, filter_status, fastHintline);
        Drawable drawable = getResources().getDrawable(R.drawable.down_arror);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); //设置边界
        pop = new PopWindowView(this, filter_date, filter_status, fastHintline,drawable);
        fastOnlineRecycler.setColorSchemeColors(Color.parseColor(Constant.ACTIVITY_REFRESHCOLOR));
        fastOnlineRecycler.setOnStateChangeLstener(this);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        fastOnlineRecycler.mRecyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
        fastOnlineRecycler.setLayoutManager(linearLayoutManager);
        adapter = new KuaiSuOnlineAdapter(this, mDatas);
        fastOnlineRecycler.setAdapter(adapter);
        adapter.setOnItemClickLitener(new RefreshBaseAdapter.OnItemClickLitener() {
            @Override
            public void onItemClick(View view, int position) {
                if (position < mDatas.size()) {
                    currEntity = mDatas.get(position);
//                    if("2".equals(currEntity.getTaskType())){//六张直接进详情
//                        loadDetail();
//                        return;
//                    }
                    String operation = currEntity.getMessageOperation();
                    final Integer op = Integer.valueOf(operation);
                    SweetAlertDialog sweetDialog = new SweetAlertDialog(KuaiSuOnLineActivity.this);
                    String title = "";
                    String content = "";
                    String confirmText = "";
                    String cancelText = "";
                    SweetAlertDialog.OnSweetClickListener confirmListener = new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                            sweetAlertDialog.dismiss();
                            String status = currEntity.getStatus();
                            if (op == 4 || op == 8) {
                                presenter.claimCheckTask(String.valueOf(appContext.getUser().getUserId()), currEntity.getID(), "type", "ShenHeRenling");
                            } else if (op == 3) {
                                presenter.claimTask(String.valueOf(appContext.getUser().getUserId()), currEntity.getID(), "type", "renling", -1);
                            } else {
                                if ("2".equals(status)) {
                                    loadDetail();
                                } else {
                                    presenter.claimTask(String.valueOf(appContext.getUser().getUserId()), currEntity.getID(), "type", "renling", op);
                                }
                            }

                        }
                    };
                    SweetAlertDialog.OnSweetClickListener cancelListener = new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                            sweetAlertDialog.dismiss();
                        }
                    };
                    if (op != 6) {
                        switch (op) {
                            case 1://待评估
                                title = "确认任务";
                                content = "VIN:" + currEntity.getVin() + "\r\n" + "\r\n" + "城市:" + currEntity.getProvName() + "-" + currEntity.getCityName();
                                confirmText = "确定";
                                cancelText = "取消";
                                break;
                            case 2://待评估，被别人退回
                                content = "此订单之前由" + currEntity.getNickname() + "退回！是否操作此订单？" + "\r\n" + "\r\n" +
                                        (TextUtils.isEmpty(currEntity.getTaskBackReason()) ? "" : currEntity.getTaskBackReason());
                                confirmText = "确定";
                                cancelText = "取消";
                                break;
                            case 3://已认领过 （总部评估师）
                                content = "此订单已被" + currEntity.getNickname() + "认领！是否操作此订单？";
                                confirmText = "确定";
                                cancelText = "取消";
                                break;
                            case 4://总部审核（被驳回过）
                                content = "此订单之前由" + currEntity.getShenheName() +
                                        "审核驳回！是否操作此订单？" + "\r\n" + "\r\n" +
                                        (TextUtils.isEmpty(currEntity.getAppraiseBackReason()) ? "" : currEntity.getAppraiseBackReason());
                                confirmText = "确定";
                                cancelText = "取消";
                                break;
                            case 5://已认领（非总部）
                                content = "此订单已被" + currEntity.getNickname() + "认领!";
                                confirmText = "关闭";
                                break;
                            case 7://已被XXX审核！
                                content = "此订单正在被" + currEntity.getShenheName() + "审核!";
                                confirmText = "关闭";
                                break;
                            case 8://弹出是否确认审核
                                title = "确认审核";
                                content = "是否确认审核该订单?";
                                confirmText = "确定";
                                cancelText = "取消";
                                break;
                        }
                        sweetDialog.setTitleText(title);
                        if (!TextUtils.isEmpty(title)) {
                            sweetDialog.setTitleText(title);
                        }
                        if (!TextUtils.isEmpty(content)) {
                            sweetDialog.setContentText(content);
                        }
                        if (!TextUtils.isEmpty(confirmText)) {
                            sweetDialog.setConfirmText(confirmText);
                            if (op == 5 || op == 7) {
                                sweetDialog.setConfirmClickListener(cancelListener);
                            } else {
                                sweetDialog.setConfirmClickListener(confirmListener);
                            }
                        }
                        if (!TextUtils.isEmpty(cancelText)) {
                            sweetDialog.setCancelText(cancelText);
                            sweetDialog.setCancelClickListener(cancelListener);
                        }
                        sweetDialog.show();
                    } else {//op==6 直接进详情
                        loadDetail();
                    }
                }
            }
        });
    }

    private void loadDetail() {
        currEntity.setReplyCount("0");
        showDialog();
        presenter.loadDetail(user.getUserId() + "", currEntity.getID(), currEntity.getTaskType());
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (LocalData.isRefresh && appContext.isNetWork) {

            fastOnlineRecycler.post(new Runnable() {
                @Override
                public void run() {
                    fastOnlineRecycler.setRefreshing(true);
                }
            });
            LocalData.isRefresh = false;//关闭刷新
            onRefresh();
        } else {
            fastOnlineRecycler.setRefreshing(false);//停止显示加载动画

            if (mDatas!=null && mDatas.size()>0){
                dismissDialog();
            }else{
                showEmptyView(Constant.errr_net);
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        Logger.e("onPause");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LocalData.isRefresh = true;//打开刷新
        if (presenter != null)
            presenter.detachView();
        ButterKnife.unbind(this);
    }

    @OnClick({R.id.title_searchbyvin, R.id.fast_title_defaultsort, R.id.fast_advanced_filter})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.fast_title_defaultsort:
                setPopDataByDate();
                pop.controlPopWindowShow(filter_date, filter_status);
                //动态显示右侧的箭头
                Drawable drawable = getResources().getDrawable(R.drawable.up_arror);
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); //设置边界
                filter_date.setCompoundDrawables(null, null, drawable, null);//画在右边
                break;
            case R.id.fast_advanced_filter:
                if (statusData != null) {
                    setPopDataByStatus();
                    pop.controlPopWindowShow(filter_status, filter_date);
                } else {
                    MyToast.showShort("无筛选数据");
                }
                //动态显示右侧的箭头
                Drawable drawable1 = getResources().getDrawable(R.drawable.up_arror);
                drawable1.setBounds(0, 0, drawable1.getMinimumWidth(), drawable1.getMinimumHeight()); //设置边界
                filter_status.setCompoundDrawables(null, null, drawable1, null);//画在右边
                break;
            case R.id.title_searchbyvin:
                Bundle bd = new Bundle();
                bd.putInt("source", 1);
                ActivityHelp.startActivity(this,OnLineSearchByVINActivity.class,"bd",bd);
                break;
            default:
                break;
        }

    }

    private void setPopDataByStatus() {
        List<PopListDataModel> mSortList = new ArrayList<PopListDataModel>();

        for (int i = 0; i < statusData.getItemList().getStatusInfo().getItem().size(); i++) {
            String value = statusData.getItemList().getStatusInfo().getItem().get(i).getValue();
            String valueID = statusData.getItemList().getStatusInfo().getItem().get(i).getId();
            if (i == 0) {
                mSortList.add(new PopListDataModel(value, valueID,
                        R.color.text_blue));
            } else {
                mSortList.add(new PopListDataModel(value, valueID,
                        R.color.light_grey_text));
            }
        }
        pop.setData(mSortList);
    }

    private void setPopDataByDate() {
        List<PopListDataModel> mSortList = new ArrayList<PopListDataModel>();
        mSortList.add(new PopListDataModel("全部任务", "0", R.color.text_blue));
        mSortList.add(new PopListDataModel("今日任务", "1", R.color.light_grey_text));
        mSortList.add(new PopListDataModel("昨日任务", "2", R.color.light_grey_text));
        pop.setData(mSortList);
    }

    @Override
    public void onRefresh() {
        operation = Constant.LISTVIEW_DEFAULT;
        presenter.resetPageIndex();
        if (appContext.isNetWork) {
            presenter.loadDataNew(user.getUserId() + "", datetype + "", status, operation + "", "", "0", "");
        } else {
            fastOnlineRecycler.setRefreshing(false);//停止显示加载动画
            if (mDatas!=null && mDatas.size()>0){
                dismissDialog();
                MyToast.showShort(Constant.errr_net);
            }else{
                showEmptyView(Constant.errr_net);
            }
        }
    }

    @Override
    public void onBottom() {
        operation = Constant.LISTVIEW_LOAD_MORE;
        if (appContext.isNetWork) {
            if (mDatas.size() > 0) {
                presenter.loadDataNew(user.getUserId() + "", datetype + "", status, operation + "", mDatas.get(mDatas.size() - 1).getID(), "0", "");
            }
        } else {
            fastOnlineRecycler.setAdapterLastState(RefreshRecycleView.STATE_UP_FAILED);
        }
    }


    @Override
    public void showError(String error) {
        if (fastOnlineRecycler == null){
            fastOnlineRecycler = (RefreshRecycleView) this.findViewById(R.id.fast_online_recycler);
        }

        fastOnlineRecycler.setRefreshing(false);//停止显示加载动画
        if (error != null) {
            if (error.startsWith("1")) {
                //设置最后一行显示加载失败
                fastOnlineRecycler.setAdapterLastState(RefreshRecycleView.STATE_UP_FAILED);
            } else {
                MyToast.showShort(Constant.errr_net);
                dismissDialog();
            }
        }

    }

    @Override
    public void showData(FastOnlineData fastOnlineData) {
        if (fastOnlineData.getStatus() == Constant.SUCCESS) {
            if (fastOnlineData.getAppraiseList().size() == 0) {
                fastEmptyView.setVisibility(View.VISIBLE);
                fastOnlineRecycler.setVisibility(View.GONE);
            } else {
                fastEmptyView.setVisibility(View.GONE);
                fastOnlineRecycler.setVisibility(View.VISIBLE);
                mDatas.clear();
                mDatas.addAll(fastOnlineData.getAppraiseList());
                adapter.updateData(mDatas);
            }
        } else {
            MyToast.showShort(fastOnlineData.getMsg());
        }
        fastOnlineRecycler.setRefreshing(false);//停止显示加载动画

    }

    @Override
    public void showMoreData(FastOnlineData fastOnlineData) {
        operation = Constant.LISTVIEW_DEFAULT;
        if (fastOnlineData.getStatus() == Constant.SUCCESS) {
            fastOnlineRecycler.setRefreshing(false);
            if (fastOnlineData.getAppraiseList().size() == 0) {
                fastOnlineRecycler.setAdapterLastState(RefreshRecycleView.STATE_NO_MORE);
            } else {
                mDatas.addAll(fastOnlineData.getAppraiseList());
                adapter.updateData(mDatas);
                fastOnlineRecycler.setAdapterLastState(RefreshRecycleView.STATE_UP_LOADEMORE);
//            showMessage("加载了" + fastOnlineData.getAppraiseList().size() + "条数据", 500);
            }
        } else {
            MyToast.showShort(fastOnlineData.getMsg());
        }
    }

    /**
     * 获取车辆详细信息
     *
     * @param carDetails
     */
    @Override
    public void showDetail(CarDetails carDetails, String type) {
        dismissDialog();
        LocalData.isRefresh = true;
        Intent intent;
        if (type.equals("1")) {
            intent = new Intent(KuaiSuOnLineActivity.this, FastOnlineCheckActivity1.class);
        } else {
            intent = new Intent(KuaiSuOnLineActivity.this, TaskDetailActivity.class);
        }
        intent.putExtra("carDetails", carDetails);
        intent.putExtra("IsDl", user.getIsShowContact());
        intent.putExtra(Constant.VIN_STATE, carDetails.getIsAccident());
        intent.putExtra(Constant.ORDER_STATUS, currEntity.getStatus());
        startActivity(intent);
    }

    @Override
    public void claimSucceed() {
        LocalData.isRefresh = true;
        currEntity.setStatus("1"); // 1: 已认领， 修改状态
        loadDetail();
    }


    @Override
    public void claimFailed(String message) {
        SweetAlertDialog dialog = new SweetAlertDialog(KuaiSuOnLineActivity.this);
        dialog.setTitleText(message);
        dialog.setConfirmText("关闭");
        dialog.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
            @Override
            public void onClick(SweetAlertDialog sweetAlertDialog) {
                sweetAlertDialog.dismiss();
            }
        });
        dialog.show();
        onRefresh();
    }

    @Override
    public void dataFailed(String message) {
        dismissDialog();
        MyToast.showShort(message);
    }

    @Override
    public void qiangdan(final String taskId, String msg) {
        SweetAlertDialog dialog = new SweetAlertDialog(KuaiSuOnLineActivity.this);
        dialog.setTitleText(msg);
        dialog.setConfirmText("确认");
        dialog.setCancelText("取消");
        dialog.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
            @Override
            public void onClick(SweetAlertDialog sweetAlertDialog) {
                sweetAlertDialog.dismiss();
                presenter.claimTask(String.valueOf(appContext.getUser().getUserId()), taskId, "type", "renling", -1);
            }
        });
        dialog.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
            @Override
            public void onClick(SweetAlertDialog sweetAlertDialog) {
                sweetAlertDialog.dismiss();
            }
        });
        dialog.show();

//        onRefresh();
    }

    @Override
    public void showEmptyView(String msg) {
        dismissDialog();
//        Toast.makeText(KuaiSuOnLineActivity.this, Constant.errr_net, Toast.LENGTH_SHORT).show();
        if(fastEmptyView!=null&&fastOnlineRecycler!=null){
            fastEmptyView.setVisibility(View.VISIBLE);
            fastOnlineRecycler.setVisibility(View.GONE);
        }

    }

    /**
     * 筛选数据回调方法
     *
     * @param status1
     * @param position
     */
    @Override
    public void filter_date(int status1, int position) {
        super.filter_date(status1, position);

        if (filter_date.getId() == status1) {
            if (position == 0) {
                //全部任务
                datetype = Constant.ALL_TASK;
                MobclickAgent.onEvent(KuaiSuOnLineActivity.this, "pinggushi_xianshangquanburenwu");//友盟统计
            } else if (position == 1) {
                //今日任务
                datetype = Constant.TODAY_TASK;
                MobclickAgent.onEvent(KuaiSuOnLineActivity.this, "pinggushi_xianshangjinrirenwu");//友盟统计
            } else if (position == 2) {
                //昨日任务
                datetype = Constant.YESTERDAY_TASK;
                MobclickAgent.onEvent(KuaiSuOnLineActivity.this, "pinggushi_xianshangzuorirenwu");//友盟统计
            }
            Drawable drawable = getResources().getDrawable(R.drawable.down_arror);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); //设置边界
            filter_date.setCompoundDrawables(null, null, drawable, null);//画在右边
        } else {
            //点击了状态筛选
            status = statusData.getItemList().getStatusInfo().getItem().get(position).getId();
            MobclickAgent.onEvent(KuaiSuOnLineActivity.this, youmeng[position]);//友盟统计
            Drawable drawable = getResources().getDrawable(R.drawable.down_arror);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); //设置边界
            filter_status.setCompoundDrawables(null, null, drawable, null);//画在右边
        }
        onRefresh();
    }

}
